//
//  LoginViewController.m
//  ECBBusinessCamp
//
//  Created by rimi on 16/6/15.
//  Copyright © 2016年 邓毕华. All rights reserved.
//

#import "LoginViewController.h"

#import "HomeViewController.h"
#import "MainViewController.h"

#define ACCOUNT @"account"
#define PASSWORD @"password"
#define ISREMEMBER @"isremember"

@interface LoginViewController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *accountTextField; // 账户文本输入框
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField; // 密码文本输入框
@property (weak, nonatomic) IBOutlet UIButton *loginBtn; // 登录按钮

@end

@implementation LoginViewController

#pragma mark 🌷🌷🌷life cycle🌷🌷🌷
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    // 是否有保存密码
    [self isRememberUserInfo];
    // 添加键盘监听
    [self addKeyNotification];
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark 🌷🌷🌷touches🌷🌷🌷
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark 🌷🌷🌷UITextFieldDelegate🌷🌷🌷
// 响应return键
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.tag == 10) {
        [_passwordTextField becomeFirstResponder];
    } else {
        [self responseToLoginBtn:_loginBtn];
    }
    return true;
}

#pragma mark 🌷🌷🌷event response🌷🌷🌷
// 登录按钮单击事件
- (IBAction)responseToLoginBtn:(id)sender {
    NSString * account = _accountTextField.text;
    NSString * password = _passwordTextField.text;
    if (account.length == 0 || password.length == 0) {
        [MBProgressHUD showError:@"用户名或密码为空！"];
    } else {
        NSMutableDictionary * parameters = [NSMutableDictionary dictionary];
        parameters[@"loginUsername"] = account;
        parameters[@"loginPassword"] = password;
        parameters[@"qiang"] = @"qiang";
        [[NetTool sharedTool] requestMethod:POST loadingMsg:@"登录中..." url:BASEURLAPPEND(LOGIN_URL) parameters:parameters finish:^(id responseObject, NSError *error) {
            if (error == nil) {
                NSDictionary * dic = responseObject;
                if ([dic[@"status"] intValue] == 100) {
                    [MBProgressHUD showSuccess:@"登录成功！"];
                    [[NSUserDefaults standardUserDefaults] setObject:responseObject[@"sid"] forKey:@"sid"];
                    [self loginSuccess:dic];
                } else {
                    [MBProgressHUD showError:@"账号或密码错误！"];
                }
            } else {
                [MBProgressHUD showError:[[NSString stringWithFormat:@"%@", error] containsString:@"The request timed out."] ? @"登录超时" : @"I don't know"];
            }
        }];
    }
}

#pragma mark 🌷🌷🌷private methods🌷🌷🌷
// 登录成功
- (void)loginSuccess:(NSDictionary *)result {
    // 保存登录用户信息
    NSDictionary *data = result[@"data"];
    [[NSUserDefaults standardUserDefaults] setObject:data[@"head"] forKey:@"head"];
    [[NSUserDefaults standardUserDefaults] setObject:data[@"nikename"] forKey:@"nikename"];
    [[NSUserDefaults standardUserDefaults] setObject:data[@"token"] forKey:@"token"];
    [[NSUserDefaults standardUserDefaults] setObject:data[@"userid"] forKey:@"uid"];
    [[NSUserDefaults standardUserDefaults] setObject:data[@"username"] forKey:@"username"];

    [LoginUserInfo defaultUserInfo].head = data[@"head"];
    [LoginUserInfo defaultUserInfo].nikename = data[@"nikename"];
    [LoginUserInfo defaultUserInfo].token = data[@"token"];
    [LoginUserInfo defaultUserInfo].userid = data[@"userid"];
    [LoginUserInfo defaultUserInfo].username = data[@"username"];
    [LoginUserInfo defaultUserInfo].sid = result[@"sid"];
    
    // 记住密码
    [[NSUserDefaults standardUserDefaults] setObject:_accountTextField.text forKey:ACCOUNT];
    [[NSUserDefaults standardUserDefaults] setObject:_passwordTextField.text forKey:PASSWORD];
    [[NSUserDefaults standardUserDefaults] setObject:@"YES" forKey:ISREMEMBER];
    
    // 添加首页视图与控制器
    HomeViewController * homePageVc = [[HomeViewController alloc] init];
    MainViewController * mainVc = (MainViewController *)self.parentViewController;
    UIButton * seletBtn = [mainVc.tabBarView viewWithTag:mainVc.tabBarView.selectedBtnIndex];
    seletBtn.selected = NO;
    UIButton * firstBtn = [mainVc.tabBarView viewWithTag:10];
    firstBtn.selected = YES;
    mainVc.tabBarView.selectedBtnIndex = 10;
    [mainVc addChildViewController:homePageVc];
    [mainVc.view insertSubview:homePageVc.view atIndex:1];
    
    // 移除登录视图和控制器
    [self.view.superview removeFromSuperview];
    [self removeFromParentViewController];
}
// 是否有保存密码
- (void)isRememberUserInfo {
    if ([[NSUserDefaults standardUserDefaults] boolForKey:ISREMEMBER]) {
        _accountTextField.text = [[NSUserDefaults standardUserDefaults] stringForKey:ACCOUNT];
        _passwordTextField.text = [[NSUserDefaults standardUserDefaults] stringForKey:PASSWORD];
    }
}
// 添加键盘监听
- (void)addKeyNotification {
    NSNotificationCenter * notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self selector:@selector(keyboardFrameWillAppear:) name:UIKeyboardWillShowNotification object:nil];
    [notificationCenter addObserver:self selector:@selector(keyboardFrameWillHidden:) name:UIKeyboardWillHideNotification object:nil];
}
// 键盘将要显示
- (void)keyboardFrameWillAppear:(NSNotification *)notification {
    [self viewChange:notification.userInfo hiddenSig:NO];
}
// 键盘将要隐藏
- (void)keyboardFrameWillHidden:(NSNotification *)notification {
    [self viewChange:notification.userInfo hiddenSig:YES];
}
// 视图上移动画
- (void)viewChange:(NSDictionary *)dic hiddenSig:(BOOL)hiddenSign {
    // 动画时长
    double duration = [dic[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    // 动画效果
    NSInteger intValue = [dic[UIKeyboardAnimationCurveUserInfoKey] integerValue];
    UIViewAnimationOptions animationOption = intValue;
    // 键盘frame
    CGRect frame = [dic[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    // 登录按钮最大Y值
    double login_Y = SCREEN_HEIGHT - CGRectGetMaxY(_loginBtn.frame) - 20;
    // 键盘多出来的高度
    double disY = CGRectGetHeight(frame) - login_Y;
    [UIView animateWithDuration:duration delay:0 options:animationOption animations:^{
        if (hiddenSign) {
            // 键盘将要隐藏
            self.view.center = CGPointMake(SCREEN_WIDTH * 0.5, SCREEN_HEIGHT * 0.5);
        } else {
            // 键盘将要显示
            self.view.center = CGPointMake(SCREEN_WIDTH * 0.5, SCREEN_HEIGHT * 0.5 - disY);
        }
    } completion:nil];
}

@end
